package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

type User struct {
	Uid   int
	Name  string
	Phone string
}

var u User

func init() {
	db, _ = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/chapter4")
	rows, err := db.Query("select `uid` from `user` where uid > ?", 0)
	if err != nil {
		fmt.Printf("query failed: %v\n", err)
	}
	println(rows)
}

// 单行测试
func queryRow() {
	err := db.QueryRow("select uid, name, phone from `user` where uid=?", 1).Scan(&u.Uid, &u.Name, &u.Phone)
	if err != nil {
		fmt.Printf("scan failed: %v\n", err)
	}
	fmt.Printf("uid:%d name:%s phone:%s\n", u.Uid, u.Name, u.Phone)
}

func insertRow() {
	// Exec() 方法用于执行一次命令（查询、删除、更新、插入等）
	ret, err := db.Exec("insert into user(name,phone) values(?,?)", "王五", "13800138001")
	if err != nil {
		fmt.Printf("insert failed: %v\n", err)
		return
	}
	uid, err := ret.LastInsertId()
	if err != nil {
		fmt.Printf("get lastinsert ID failed: %v\n", err)
		return
	}
	fmt.Printf("inset success, the id is %d.\n", uid)
}

func updateRow() {
	ret, err := db.Exec("update user set name=? where uid=?", "张三", 1)
	if err != nil {
		fmt.Printf("update row failed: %v\n", err)
		return
	}
	n, err := ret.RowsAffected()
	if err != nil {
		fmt.Printf("get RowsAffected failed: %v\n", err)
		return
	}
	fmt.Printf("update row success, affected rows:%d\n", n)
}

func main() {
	queryRow()
	insertRow()
	updateRow()
}
